package com.gc.cscott.util;

import java.io.*;
import java.text.*;
import java.util.Date;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;
import java.util.logging.SimpleFormatter;
import org.apache.commons.lang.StringUtils;

/**
 *
 * @author root
 */
public class CscottFomatter extends Formatter {
    Date date = new Date();

    final SimpleDateFormat timeFormatter = new SimpleDateFormat("HH:mm:ss");

    // Line separator string.  This is the value of the line.separator
    // property at the moment that the SimpleFormatter was created.
    private String lineSeparator = System.getProperty("line.separator");

    /**
     * Format the given LogRecord.
     * @param record the log record to be formatted.
     * @return a formatted log record
     */
    public synchronized String format(LogRecord record) {
        StringBuilder result = new StringBuilder();
        // Minimize memory allocations here.
        date.setTime(record.getMillis());
        result.append(timeFormatter.format(date));
        result.append(" ");
        result.append(StringUtils.rightPad(record.getLevel().getName(), 7));
        final String source;
        if (record.getSourceClassName() != null) {
            String className = record.getSourceClassName();
            int index = className.lastIndexOf('.');
            if (index>=0){
                className = className.substring(index+1);
            }
            source = className;
            
        } else {
            source=record.getLoggerName();
        }
        result.append(StringUtils.rightPad(source, 30));
        //if (record.getSourceMethodName() != null) {
        //    result.append(" ");
        //    result.append(record.getSourceMethodName());
        //}
        //result.append(lineSeparator);
        
        String message = formatMessage(record);
        result.append(": ");
        result.append(message);
        result.append(lineSeparator);
        if (record.getThrown() != null) {
            try {
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                record.getThrown().printStackTrace(pw);
                pw.close();
                result.append(sw.toString());
            } catch (Exception ex) {
            }
        }
        return result.toString();
    }
}
